import React, { useEffect, useMemo, useState, useRef, useCallback } from 'react'
import { Input } from 'antd';
import { Carousel } from 'antd';
import one from '../../assets/1.png'
import two from '../../assets/2.png'
import three from '../../assets/3.png'
import four from '../../assets/4.png'
// import doctor from '../../assets/doctor.png'
// import yue from '../../assets/预约挂号.png'
// import ji from '../../assets/极速问诊.png'
// import fu from '../../assets/复诊开房费.png'
// import yongyao from '../../assets/用药建议.png'
// import suifang from '../../assets/随访计划.png'
// import wode from '../../assets/我的医生.png'
import gong from '../../assets/shop.png'
import hua from '../../assets/华领医药.png'
import lan from '../../assets/蓝素.png'
import wan from '../../assets/万全药业.png'
import tong from '../../assets/同仁堂.png'
import aa from '../../assets/延时持久.png'
import bb from '../../assets/止脱生发.png'
import cc from '../../assets/cc.png'
import dd from '../../assets/dd.png'
import ee from '../../assets/ee.png'
import ff from '../../assets/ff.png'
import gg from '../../assets/gg.png'
import hh from '../../assets/hh.png'
import ii from '../../assets/ii.png'
import jj from '../../assets/jj.png'

import { useNavigate } from 'react-router-dom';
import { Button } from 'antd';
import axios from '../../api/http'

// 隐藏滚动条的CSS样式
const hideScrollbarStyle = `
  .hide-scrollbar::-webkit-scrollbar {
    display: none;
  }
`

// 注入样式
if (typeof document !== 'undefined') {
  const style = document.createElement('style')
  style.textContent = hideScrollbarStyle
  document.head.appendChild(style)
}

function Index() {
  const nav=useNavigate()
  const { Search } = Input;
  const onSearch= () => console.log();
  const contentStyle: React.CSSProperties = {
  height: '160px',
  color: '#fff',
  lineHeight: '160px',
  textAlign: 'center',
  background: '#364d79',
};

  // 背景图片铺满样式示例
  // const backgroundImageStyle: React.CSSProperties = { width:'100%', height:'200px', backgroundImage:`url(${one})`, backgroundSize:'cover', backgroundPosition:'center', backgroundRepeat:'no-repeat' };

  const categories = [
    { name: '延时持久', icon: aa },
    { name: '止脱生发', icon: bb },
    { name: '妇科炎症', icon: cc },
    { name: '平稳降压', icon: dd },
    { name: '稳控血糖', icon: ee },
    { name: '领券中心', icon: ff },
    { name: '快速降脂', icon: gg },
    { name: '缓解风湿', icon: hh },
    { name: '远离哮喘', icon: ii },
    { name: '全部分类', icon: jj },
    // 第二页的分类（重复使用图标进行演示）
    { name: '感冒发烧', icon: aa },
    { name: '肠胃调理', icon: bb },
    { name: '皮肤护理', icon: cc },
    { name: '心血管', icon: dd },
    { name: '糖尿病', icon: ee },
    { name: '优惠活动', icon: ff },
    { name: '保健品', icon: gg },
    { name: '医疗器械', icon: hh },
    { name: '母婴用品', icon: ii },
    { name: '更多分类', icon: jj },
  ]
  
  // 商品分区 Tabs
  const productTabs = useMemo(() => ([
    { key: 'hot', title: '精选热销' },
    { key: 'male', title: '男性健康' },
    { key: 'female', title: '女性养护' },
    { key: 'home', title: '家庭常备' }
  ]), [])
  const [activeTab, setActiveTab] = useState('hot')
  type Goods = { id?: string|number, image?: string, cover?: string, name?: string, title?: string, price?: number, salePrice?: number, tag?: string }
  const [goods, setGoods] = useState<Goods[]>([])
  const [loading, setLoading] = useState(false)
  const scrollContainerRef = useRef<HTMLDivElement>(null)
  const [canScrollLeft, setCanScrollLeft] = useState(false)
  const [canScrollRight, setCanScrollRight] = useState(false)
  const categoryScrollRef = useRef<HTMLDivElement>(null)
  const [categoryScrollLeft, setCategoryScrollLeft] = useState(false)
  const [categoryScrollRight, setCategoryScrollRight] = useState(false)
  const [currentPage, setCurrentPage] = useState(0)
  const itemsPerPage = 10 // 每页10个分类
  const totalPages = Math.ceil(categories.length / itemsPerPage)

  useEffect(() => {
    const fetchGoods = async () => {
      setLoading(true)
      try {
        const url = activeTab === 'hot' ? '/restorative/list' : '/drug/list'
        const params = activeTab === 'hot' ? { pageCode:1, pageSize:10 } : { category: activeTab, pageCode:1, pageSize:10 }
        const res = await axios.get(url, { params })
        const raw = res as unknown as { data?: Goods[] | Goods; list?: Goods[] | Goods }
        const data = raw?.data ?? raw?.list ?? []
        // 接口可能返回对象或数组，这里统一成数组
        const normalized = Array.isArray(data) ? data : (data ? [data] : [])
        setGoods(normalized)
      } catch {
        setGoods([])
      } finally {
        setLoading(false)
      }
    }
    fetchGoods()
  }, [activeTab])

  // 检查滚动状态
  const checkScrollStatus = () => {
    const container = scrollContainerRef.current
    if (container) {
      const { scrollLeft, scrollWidth, clientWidth } = container
      setCanScrollLeft(scrollLeft > 0)
      setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 1)
    }
  }

  // 滚动到指定位置
  const scrollTo = (direction: 'left' | 'right') => {
    const container = scrollContainerRef.current
    if (container) {
      const scrollAmount = 200 // 每次滚动的距离
      const currentScroll = container.scrollLeft
      const targetScroll = direction === 'left' 
        ? Math.max(0, currentScroll - scrollAmount)
        : currentScroll + scrollAmount
      
      container.scrollTo({
        left: targetScroll,
        behavior: 'smooth'
      })
    }
  }

  // 监听滚动事件
  useEffect(() => {
    const container = scrollContainerRef.current
    if (container) {
      checkScrollStatus() // 初始检查
      container.addEventListener('scroll', checkScrollStatus)
      return () => container.removeEventListener('scroll', checkScrollStatus)
    }
  }, [goods]) // 当商品数据变化时重新检查

  // 检查分类滚动状态
  const checkCategoryScrollStatus = useCallback(() => {
    const container = categoryScrollRef.current
    if (container) {
      const { scrollLeft, scrollWidth, clientWidth } = container
      setCategoryScrollLeft(scrollLeft > 0)
      setCategoryScrollRight(scrollLeft < scrollWidth - clientWidth - 1)
      
      // 计算当前页
      const categoryWidth = 60
      const gap = 16
      const pageWidth = (categoryWidth + gap) * 5
      const newPage = Math.round(scrollLeft / pageWidth)
      if (newPage !== currentPage && newPage >= 0 && newPage < totalPages) {
        setCurrentPage(newPage)
      }
    }
  }, [currentPage, totalPages])

  // 分类滚动到指定位置
  const scrollCategoryTo = (direction: 'left' | 'right') => {
    const container = categoryScrollRef.current
    if (container) {
      // 计算一页的宽度：5个分类的宽度 + 间距
      const categoryWidth = 60 // 分类图标宽度
      const gap = 16 // 分类间距
      const pageWidth = (categoryWidth + gap) * 5 // 一页的宽度（5个分类）
      
      let newPage = currentPage
      if (direction === 'left' && currentPage > 0) {
        newPage = currentPage - 1
      } else if (direction === 'right' && currentPage < totalPages - 1) {
        newPage = currentPage + 1
      }
      
      if (newPage !== currentPage) {
        setCurrentPage(newPage)
        const targetScroll = newPage * pageWidth
        
        container.scrollTo({
          left: targetScroll,
          behavior: 'smooth'
        })
      }
    }
  }

  // 监听分类滚动事件
  useEffect(() => {
    const container = categoryScrollRef.current
    if (container) {
      checkCategoryScrollStatus() // 初始检查
      container.addEventListener('scroll', checkCategoryScrollStatus)
      return () => container.removeEventListener('scroll', checkCategoryScrollStatus)
    }
  }, [checkCategoryScrollStatus]) // 添加依赖
  return (
    <div style={{background:'#fff',minHeight:'100vh'}}>
      <div style={{overflow:'auto',backgroundColor:'#ffff',
    position:'fixed',top:'0px',left:'0',width:'100%',zIndex:1000}}>
      <p style={{textAlign:'center',margin:'12px 0',fontSize:'16px'}}>妙手商场</p>
  <div style={{display:'flex',alignItems:'center',gap:'8px',padding:'0 12px'}}>
    <div style={{flex:1}}>
      <Search
  style={{border:'1.5px solid #ff6b00',borderRadius:'999px',overflow:'hidden',boxShadow:'none',outline:'none'}}
      placeholder="米若地尔搽剂"
      allowClear
      enterButton={<Button type="text" style={{display:'inline-block',padding:'4px 14px',borderRadius:'999px',background:'linear-gradient(90deg,#ff7a00,#ff4d00)',color:'#fff'}}>搜索</Button>}
      size="large"
      onSearch={onSearch}
      prefix={<span style={{color:'#bfbfbf',paddingLeft:'8px'}}>🔍</span>}
      bordered={false}
    />
    </div>
  </div>
      </div>

     <Carousel autoplay style={{marginTop:'80px'}}>
    <div onClick={()=>nav('/pin')}>
      <h3 style={contentStyle}>
        <img src={one} alt="" style={{width:'100vw'}}/>
      </h3>
    </div>
    <div>
         <img src={two} alt="" style={{width:'100vw'}}/>
    </div>
    <div>
        <img src={three} alt="" style={{width:'100vw'}}/>
    </div>
    <div>
      <img src={four} alt="" style={{width:'100vw'}}/>
    </div>
  </Carousel>

  <div style={{display:'flex',justifyContent:'space-between',padding:'10px 12px',background:'#fff9ef',borderRadius:'8px',margin:'10px 12px'}}>
    <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
      <span><img src={gong} alt="" /></span><span style={{fontSize:'12px'}}>正品保障</span>
      <span style={{color:'#ff6b00',fontSize:'12px'}}>|</span>
    </div>
    <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
      <span><img src={gong} alt="" /></span><span style={{fontSize:'12px'}}>隐私发货</span>
      <span style={{color:'#ff6b00',fontSize:'12px'}}>|</span>
    </div>
    <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
      <span><img src={gong} alt="" /></span><span style={{fontSize:'12px'}}>专业药师</span>
      <span style={{color:'#ff6b00',fontSize:'12px'}}>|</span>
    </div>
    <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
      <span><img src={gong} alt="" /></span><span style={{fontSize:'12px'}}>官网直供</span>
    </div>
  </div>

  {/* 分类横向滚动区域 */}
  <div style={{position:'relative', padding:'14px 0'}}>
    {/* 左滚动按钮 */}
    {categoryScrollLeft && (
      <div 
        onClick={() => scrollCategoryTo('left')}
        style={{
          position:'absolute',
          left:'8px',
          top:'50%',
          transform:'translateY(-50%)',
          zIndex:10,
          width:'28px',
          height:'28px',
          background:'rgba(255,255,255,0.9)',
          borderRadius:'50%',
          display:'flex',
          alignItems:'center',
          justifyContent:'center',
          color:'#666',
          fontSize:'14px',
          cursor:'pointer',
          transition:'all 0.2s',
          boxShadow:'0 2px 8px rgba(0,0,0,0.1)',
          border:'1px solid #f0f0f0'
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.background = 'rgba(255,255,255,1)'
          e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.background = 'rgba(255,255,255,0.9)'
          e.currentTarget.style.transform = 'translateY(-50%) scale(1)'
        }}
      >
        
      </div>
    )}

    {/* 右滚动按钮 */}
    {categoryScrollRight && (
      <div 
        onClick={() => scrollCategoryTo('right')}
        style={{
          position:'absolute',
          right:'8px',
          top:'50%',
          transform:'translateY(-50%)',
          zIndex:10,
          width:'28px',
          height:'28px',
          background:'rgba(255,255,255,0.9)',
          borderRadius:'50%',
          display:'flex',
          alignItems:'center',
          justifyContent:'center',
          color:'#666',
          fontSize:'14px',
          cursor:'pointer',
          transition:'all 0.2s',
          boxShadow:'0 2px 8px rgba(0,0,0,0.1)',
          border:'1px solid #f0f0f0'
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.background = 'rgba(255,255,255,1)'
          e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.background = 'rgba(255,255,255,0.9)'
          e.currentTarget.style.transform = 'translateY(-50%) scale(1)'
        }}
      >
        ›
      </div>
    )}

    {/* 分类滚动容器 */}
    <div 
      ref={categoryScrollRef}
      style={{
        display:'flex',
        gap:'16px',
        overflowX:'auto',
        padding:'0 12px',
        scrollSnapType:'x mandatory',
        scrollbarWidth:'none',
        msOverflowStyle:'none',
        scrollBehavior:'smooth'
      }}
      onScroll={checkCategoryScrollStatus}
      className="hide-scrollbar"
    >
      {/* 第一页：前5个分类 */}
      <div style={{
        display:'flex',
        flexDirection:'column',
        gap:'14px',
        flexShrink:0,
        scrollSnapAlign:'start',
        width:'380px' // 5个分类的宽度 + 间距
      }}>
        {/* 第一行 */}
        <div style={{
          display:'flex',
          gap:'16px',
          justifyContent:'space-between'
        }}>
          {categories.slice(0, 5).map((category)=> (
            <div key={category.name} style={{
              flexShrink:0,
              textAlign:'center',
              width:'60px'
            }}>
              <div style={{
                width:'60px',height:'60px',borderRadius:'50%',
                background:'#fff',
                margin:'0 auto 8px',display:'flex',alignItems:'center',justifyContent:'center',
                overflow:'hidden',
                
                transition:'all 0.2s',
                cursor:'pointer'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'scale(1.05)'
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'scale(1)'
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'
              }}
              >
                <img src={category.icon} alt={category.name}
                 style={{width:'80%',height:'80%',objectFit:'cover'}}/>
              </div>
              <div style={{fontSize:'12px', color:'#333', lineHeight:1.2}}>{category.name}</div>
            </div>
          ))}
        </div>
        
        {/* 第二行 */}
        <div style={{
          display:'flex',
          gap:'16px',
          justifyContent:'space-between'
        }}>
          {categories.slice(5, 10).map((category)=> (
            <div key={category.name} style={{
              flexShrink:0,
              textAlign:'center',
              width:'60px'
            }}>
              <div style={{
                width:'60px',height:'60px',borderRadius:'50%',
                background:'#fff',
                margin:'0 auto 8px',display:'flex',alignItems:'center',justifyContent:'center',
                overflow:'hidden',
                
                transition:'all 0.2s',
                cursor:'pointer'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'scale(1.05)'
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'scale(1)'
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'
              }}
              >
                <img src={category.icon} alt={category.name}
                 style={{width:'80%',height:'80%',objectFit:'cover'}}/>
              </div>
              <div style={{fontSize:'12px', color:'#333', lineHeight:1.2}}>{category.name}</div>
            </div>
          ))}
        </div>
        
      </div>
    </div>

    {/* 分页指示器 */}
    <div style={{
      display:'flex',
      justifyContent:'center',
      gap:'4px',
      marginTop:'12px',
      padding:'0 12px'
    }}>
      {Array.from({ length: totalPages }, (_, index) => (
        <div key={index} style={{
          width: index === currentPage ? '20px' : '8px',
          height:'4px',
          background: index === currentPage ? '#ff6b00' : '#ddd',
          borderRadius:'2px',
          transition:'all 0.3s'
        }}></div>
      ))}
    </div>
  </div>
{/* 品牌专区 */}
  <div style={{fontWeight:700,fontSize:'18px',padding:'12px'}}>品牌专区</div>
  <div style={{display:'flex',gridTemplateColumns:'repeat(2, 1fr)',gap:'12px',padding:'0 12px 24px'}}>
    {[hua,lan,wan,tong].map((img, i)=> (
      <div key={i} style={{background:'#fff',borderRadius:'12px',padding:'12px',textAlign:'center'}}>
        <img src={img} alt="brand" style={{width:'100%',height:'auto'}}/>
      </div>
    ))}
  </div>

  {/* 商品 Tabs */}
  <div style={{display:'flex',gap:'18px',padding:'6px 12px 0'}}>
    {productTabs.map(t => (
      <div key={t.key} onClick={()=>setActiveTab(t.key)} style={{position:'relative',padding:'8px 4px',cursor:'pointer',fontSize:'18px',fontWeight:700,color: activeTab===t.key ? '#000' : '#666'}}>
        {t.title}
        {activeTab===t.key && (
          <span style={{position:'absolute',left:0,bottom:0,height:'3px',width:'28px',background:'#ff4d00',borderRadius:'3px'}}></span>
        )}
      </div>
    ))}
  </div>

  {/* 商品列表 - 横向滚动卡片 */}
  <div style={{padding:'10px 0 80px', position:'relative'}}>
    {loading ? (
      <div style={{textAlign:'center',color:'#999',padding:'20px 0'}}>加载中...</div>
    ) : (
      <>
        {/* 左滚动按钮 */}
        {canScrollLeft && (
          <div 
            onClick={() => scrollTo('left')}
            style={{
              position:'absolute',
              left:'8px',
              top:'50%',
              transform:'translateY(-50%)',
              zIndex:10,
              width:'32px',
              height:'32px',
              background:'rgba(0,0,0,0.6)',
              borderRadius:'50%',
              display:'flex',
              alignItems:'center',
              justifyContent:'center',
              color:'#fff',
              fontSize:'16px',
              cursor:'pointer',
              transition:'all 0.2s',
              boxShadow:'0 2px 8px rgba(0,0,0,0.2)'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(0,0,0,0.8)'
              e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(0,0,0,0.6)'
              e.currentTarget.style.transform = 'translateY(-50%) scale(1)'
            }}
          >
            ‹
          </div>
        )}

        {/* 右滚动按钮 */}
        {canScrollRight && (
          <div 
            onClick={() => scrollTo('right')}
            style={{
              position:'absolute',
              right:'8px',
              top:'50%',
              transform:'translateY(-50%)',
              zIndex:10,
              width:'32px',
              height:'32px',
              background:'rgba(0,0,0,0.6)',
              borderRadius:'50%',
              display:'flex',
              alignItems:'center',
              justifyContent:'center',
              color:'#fff',
              fontSize:'16px',
              cursor:'pointer',
              transition:'all 0.2s',
              boxShadow:'0 2px 8px rgba(0,0,0,0.2)'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(0,0,0,0.8)'
              e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(0,0,0,0.6)'
              e.currentTarget.style.transform = 'translateY(-50%) scale(1)'
            }}
          >
            ›
          </div>
        )}

        {/* 滚动容器 */}
        <div 
          ref={scrollContainerRef}
          style={{
            display:'flex',
            gap:'12px',
            overflowX:'auto',
            padding:'0 12px',
            scrollSnapType:'x mandatory',
            scrollbarWidth:'none', // Firefox
            msOverflowStyle:'none', // IE/Edge
            scrollBehavior:'smooth'
          }}
          onScroll={checkScrollStatus}
          className="hide-scrollbar"
        >
          {goods.map((g, i) => {
            const cover = g?.image || g?.cover || one
            const name = g?.name || g?.title || '药品'
            const price = g?.price || g?.salePrice || 0
            const tag = g?.tag || '多盒装'
            return (
              <div key={g.id || `good-${i}`} style={{
                background:'#fff',
                borderRadius:'12px',
                padding:'10px',
                boxShadow:'0 2px 8px rgba(0,0,0,0.1)',
                minWidth:'160px',
                maxWidth:'160px',
                scrollSnapAlign:'start',
                flexShrink:0,
                transition:'all 0.2s',
                cursor:'pointer'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-2px)'
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.15)'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)'
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'
              }}
              > 
                <div style={{height:'140px',display:'flex',alignItems:'center',justifyContent:'center',overflow:'hidden',borderRadius:'8px',background:'#fafafa'}} onClick={()=>nav(`/detail?id=${g.id ?? i}`)}>
                  <img src={cover} alt={name} style={{maxWidth:'100%',maxHeight:'100%',objectFit:'contain'}}/>
                </div>
                <div style={{marginTop:'8px',fontSize:'14px',color:'#222',lineHeight:1.4,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{name}</div>
                <div style={{marginTop:'6px'}}>
                  <span style={{display:'inline-block',border:'1px solid #ff6b00',color:'#ff6b00',padding:'2px 6px',borderRadius:'6px',fontSize:'12px'}}>{tag}</span>
                </div>
                <div style={{marginTop:'8px',color:'#ff3b30',fontWeight:700}}>¥{price}</div>
              </div>
            )
          })}
        </div>

        {/* 滚动指示器 */}
        {goods.length > 0 && (
          <div style={{
            display:'flex',
            justifyContent:'center',
            gap:'6px',
            marginTop:'12px',
            padding:'0 12px'
          }}>
            {Array.from({ length: Math.ceil(goods.length / 3) }, (_, i) => (
              <div 
                key={i}
                style={{
                  width:'8px',
                  height:'8px',
                  borderRadius:'50%',
                  background:'#ddd',
                  transition:'all 0.2s'
                }}
              />
            ))}
          </div>
        )}
      </>
    )}
  </div>
    </div>
  )
}

export default Index
